package com.lwj.filter;

import com.lwj.constant.ConstantDefinition;
import com.lwj.entity.RestEntity;
import com.lwj.log.LogRequestWrapper;
import com.lwj.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LoginFilter extends OncePerRequestFilter {
    protected static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    private AntPathMatcher matcher = new AntPathMatcher();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try{
            request=new LogRequestWrapper(request);
            boolean check=request.getSession().getAttribute(ConstantDefinition.SESSION_KEY_USERNAME) != null ||excludedPath(request);
            if (check) {
                filterChain.doFilter(request, response);
                return;
            }
        }catch (Exception e){
            logger.error("登录报错",e);
        }
        error(response,"你没有权限",401);
    }

    public Boolean excludedPath(HttpServletRequest request){
        List<String> excludedPath = new ArrayList<>(Arrays.asList(getFilterConfig().getInitParameter("excludedPath").split(",")));
        Boolean result=false;
        for (int i = 0; i < excludedPath.size(); i++) {
            String path = excludedPath.get(i);
            //?：匹配任意单个字符
            //*：匹配任意数量的字符，不包括“/”
            //**：匹配更多的目录，包括“/”
            if(matcher.match(path,request.getServletPath())){
                result=true;
                break;
            }
        }
        return result;
    }

    public void error(HttpServletResponse response,String errMsg,Integer errCode) throws IOException {
        response.setStatus(401);
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String s = JsonUtil.toJson(RestEntity.error(errMsg, errCode));
        out.append(s);
    }
}
